package arrAndstr;

import java.util.HashMap;

/*
    3. 无重复字符的最长子串-滑动窗口
 */
public class T3 {

    public static void main(String[] args) {
        String s = "pwwkew";
        System.out.println(lengthOfLongestSubstring(s));
    }
    public static int lengthOfLongestSubstring(String s) {
        int len = s.length();
        if (len==0 || len==1) {
            return len;
        }
        HashMap<Character, Integer> map = new HashMap<>();
        int result = 1;
        int leftIndex = 0;
        int rightIndex = 0;
        map.put(s.charAt(leftIndex), leftIndex);

        while (rightIndex < len-1) {
            rightIndex++;
            char newCh = s.charAt(rightIndex);

            if (!map.containsKey(newCh)) {
                map.put(newCh, rightIndex);
                result = rightIndex-leftIndex+1 > result ? rightIndex-leftIndex+1 : result;
            } else {
                // 存在，重复了
                int newChIndex = map.get(newCh);
                while (leftIndex <= newChIndex) {
                    map.remove(s.charAt(leftIndex));
                    leftIndex++;
                }
            }
            map.put(newCh, rightIndex);
        }
        return result;
    }
}
